package com.cloud.ding_talk;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.GetClient;
import com.alibaba.xxpt.gateway.shared.client.http.PostClient;
import com.cloud.ding_talk.vo.DingNotice;
import com.cloud.entity.AuthUser;
import com.cloud.exception.CustomException;
import com.cloud.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 浙政钉/专有钉钉API
 *
 * @author yzj
 */
public class DingGrantUtils {

    private final Logger logger = LoggerFactory.getLogger(DingGrantUtils.class);

    private ExecutableClient executableClient;

    /**
     * @param domainName 不同环境对应不同域名,示例为Sass 域名
     * @param accessKey  应用App Key
     * @param secretKey  应用App Secret
     */
    public DingGrantUtils(String domainName, String accessKey, String secretKey) {
        executableClient = ExecutableClient.getInstance();
        executableClient.setDomainName(domainName);
        executableClient.setProtocal("https");
        executableClient.setAccessKey(accessKey);
        executableClient.setSecretKey(secretKey);
        executableClient.setTimeout(5000);
        executableClient.init();
    }

    /**
     * 获取刷新参数AccessToken
     *
     * @return accessToken
     */
    private String getDingTalkAccessToken2() {
        String accessToken = "";
        // ExecutableClient 保证单例
        GetClient getClient = executableClient.newGetClient("/gettoken.json");
        String accessTokenData = getClient.get();
        logger.info("获取浙政钉Token信息" + accessTokenData);
        JSONObject accessTokenJsonObject = JSONObject.parseObject(accessTokenData);
        JSONObject content = accessTokenJsonObject.getJSONObject("content");
        if (content.getBoolean("success")) {
            accessToken = accessTokenJsonObject.getJSONObject("content").getJSONObject("data")
                    .getString("accessToken");
        }
        return accessToken;
    }

    /**
     * 获取浙政钉用户授权信息
     *
     * @param authCode
     * @return
     */
    public AuthUser getDingTalkUserInfo(String authCode) {
        try {
            PostClient postClient = executableClient.newPostClient("/rpc/oauth2/dingtalk_app_user.json");
            if (StringUtils.isEmpty(getDingTalkAccessToken2())) {
                throw new CustomException("请求浙政钉系统异常");
            }
            postClient.addParameter("access_token", getDingTalkAccessToken2());
            postClient.addParameter("auth_code", authCode);
            String apiResult = postClient.post();
            logger.info("浙政钉账户APP授权信息:" + apiResult);
            return getDingTalkUser(apiResult);
        } catch (Exception e) {
            throw new CustomException("授权获获取浙政钉账户信息失败:" + e);
        }
    }

    /**
     * 获取浙政钉扫码用户授权信息
     *
     * @param authCode
     * @return
     */
    public AuthUser scanDingTalkUserInfo(String authCode) {
        try {
            PostClient postClient = executableClient.newPostClient("/rpc/oauth2/getuserinfo_bycode.json");
            if (StringUtils.isEmpty(getDingTalkAccessToken2())) {
                throw new CustomException("请求浙政钉系统异常");
            }
            postClient.addParameter("access_token", getDingTalkAccessToken2());
            postClient.addParameter("code", authCode);
            String apiResult = postClient.post();
            logger.info("浙政钉账户扫码授权信息:" + apiResult);
            return getDingTalkUser(apiResult);
        } catch (Exception e) {
            throw new CustomException("授权获取浙政钉账户信息失败:" + e);
        }
    }

    /**
     * 获取浙政钉账户信息
     *
     * @param apiResult
     * @return
     */
    private AuthUser getDingTalkUser(String apiResult) {
        AuthUser authUser = null;
        JSONObject accessTokenJsonObject = JSONObject.parseObject(apiResult);
        JSONObject content = accessTokenJsonObject.getJSONObject("content");
        if (content.getBoolean("success")) {
            JSONObject resultData = accessTokenJsonObject.getJSONObject("content").getJSONObject("data");
            authUser = new AuthUser();
            authUser.setAccount(resultData.getString("account"));
            authUser.setAccountId(resultData.getString("accountId"));
            authUser.setLastName(resultData.getString("lastName"));
            authUser.setNickNameCn(resultData.getString("nickNameCn"));
            authUser.setRealmId(resultData.getString("realmId"));
            authUser.setOpenid(resultData.getString("employeeCode"));
        }
        return authUser;
    }

    /**
     * 发送浙政钉工作消息
     *
     * @param notice
     */
    public void dingTalkNotice(DingNotice notice) {
        try {
            PostClient postClient = executableClient.newPostClient("/message/workNotification");
            postClient.addParameter("receiverIds", notice.getAccountIds());
            postClient.addParameter("tenantId", notice.getTenantId());
            postClient.addParameter("bizMsgId", notice.getContentId());
            // 添加消息体内容
            JSONObject markdown = new JSONObject();
            markdown.put("title", notice.getTitle());
            markdown.put("text", notice.getContent());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msgtype", "markdown");
            jsonObject.put("markdown", markdown);
            // 发送消息体内容
            postClient.addParameter("msg", jsonObject.toString());
            String apiResult = postClient.post();
            logger.info("浙政钉发送消息:" + apiResult);
        } catch (Exception e) {
            throw new CustomException("发送浙政钉消息失败:" + e);
        }
    }

}
